package com.cloudcms.web.controller.cms;

import com.cloudcms.web.annotation.SessionId;
import com.cloudcms.web.base.redis.session.template.RedisSessionTemplate;
import com.cloudcms.web.common.BusinessException;
import com.cloudcms.web.service.CmsService;
import com.cloudcms.web.util.Constants;
import com.cloudcms.web.common.Result;
import com.cloudcms.web.entity.Admin;
import com.cloudcms.web.util.CommUtil;
import com.cloudcms.web.util.DesUtil;
import com.cloudcms.web.util.SCaptcha;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.async.DeferredResult;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;


@RestController
@RequestMapping("/admin")
public class AdminController {
    /**
     * 注入service
     */
    @Autowired
    private CmsService cmsService;

    @Autowired
    private RedisSessionTemplate session;

    @RequestMapping(value = "/execute/1.0", method = { RequestMethod.GET, RequestMethod.POST })
    public DeferredResult<String>  execute(Model model, HttpServletRequest request, HttpServletResponse response,@SessionId String sessionId) throws  Exception{
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String validcode = request.getParameter("validcode");
        String pageno = request.getParameter("pageno");
        String pagesize = request.getParameter("pagesize");
        if (StringUtils.isEmpty(username)) throw  new BusinessException(Constants.SIMPLE_RESULT_SYSTEM,"用户名[username]不能为空");
        if (StringUtils.isEmpty(password)) throw  new BusinessException(Constants.SIMPLE_RESULT_SYSTEM,"登录密码[password]不能为空");
        if (StringUtils.isEmpty(validcode)) throw  new BusinessException(Constants.SIMPLE_RESULT_SYSTEM,"图像验证码[validcode]不能为空");
        if(!validcode.toUpperCase().equals(session.getAttribute(Constants.SESSIONPREFIX+sessionId,"rand"))) throw  new BusinessException(Constants.SIMPLE_RESULT_SYSTEM,"图像验证码[validcode"+validcode+"]错误");

        pageno = StringUtils.isEmpty(pageno)?"1":pageno;
        pagesize = StringUtils.isEmpty(pagesize)?"20":pagesize;

        password = DesUtil.strDec(password,"1","2","3");
        password = CommUtil.getMd5Str(username,password);
        Admin admin = new Admin();
        admin.setUsername(username);
        admin.setPageno(Integer.parseInt(pageno));
        admin.setPagesize(Integer.parseInt(pagesize));

        List<Admin> adminList = cmsService.selectAdmin(admin);
        if (adminList.size()==0) throw new BusinessException(Constants.SIMPLE_RESULT_SYSTEM,"用户名[username]不存在");
        if(!password.equals(adminList.get(0).getPassword())) throw  new BusinessException(Constants.SIMPLE_RESULT_SYSTEM,"用户名或者密码错误");
        //if(!password.equals("c4893e29a51447d327fc86394890253b")) throw  new BusinessException(Constants.SIMPLE_RESULT_SYSTEM,"用户名或者密码错误");

        /*Set<String> keys = session.keys(Constants.SESSIONPREFIX + "*");
        //登录成功，清空username的登录信息
        for (String s : keys) {
            if(session.getAttribute(s, "login_user", Admin.class) == null) {
                continue;
            }
            Admin u = session.getAttribute(s, "login_admin", Admin.class);
            if (username.equals(u.getUsername())){
                session.delete(s);
            }
        }*/
        session.setAttribute(Constants.SESSIONPREFIX+sessionId,"login_admin",adminList.get(0));
        Result result = new Result();

        DeferredResult<String> deferredResult = new DeferredResult<String>(Constants.TIMEOUT_VALUE);
        deferredResult.setResult(result.toString());
        return deferredResult;
    }
    @RequestMapping(value = "/validcode/1.0", method = { RequestMethod.GET, RequestMethod.POST })
    public void  validcode(Model model, HttpServletRequest request, HttpServletResponse response,@SessionId String sessionId) {
        //设置响应的类型格式为图片格式
        response.setContentType("image/jpeg");
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);
        SCaptcha instance = new SCaptcha();
        session.setAttribute(Constants.SESSIONPREFIX + sessionId, "rand", instance.getCode());

        try {
            instance.write(response.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}